package com.kollway.update;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kollway.update.model.Result;

import org.apache.commons.io.IOUtils;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lyaotian on 1/20/17.
 */

public class UpdateUtil {
    public static final Gson GSON = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();
    public static final Handler uiHandler = new Handler(Looper.getMainLooper());

    public boolean onlyWifi = false;
    public boolean showToast = false;
    public boolean autoInstall = false;
    private final AppCompatActivity activity;

    private UpdateUtil(AppCompatActivity activity) {
        this.activity = activity;
    }

    public static UpdateUtil with(AppCompatActivity activity) {
        return new UpdateUtil(activity);
    }

    public UpdateUtil onlyWifi(boolean value) {
        this.onlyWifi = value;
        return this;
    }

    public UpdateUtil showToast(boolean value) {
        this.showToast = value;
        return this;
    }

    public UpdateUtil autoInstall(boolean value) {
        this.autoInstall = value;
        return this;
    }

    public void check(String baseUrl) {
        if (this.onlyWifi) {
            if (!AndroidUtil.isWifiConnect(activity)) {
                return;
            }
        }

        final String packageName = activity.getPackageName();
        final int code = AndroidUtil.getVersionCode(activity);
        final String name = AndroidUtil.getVersionName(activity);
        final String urlString = baseUrl + "/AppVersionApi/latestVersion?platform=0" +
                "&package=" + packageName +
                "&version_code=" + code +
                "&version_name=" + name;

        new Thread() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(urlString);
                    connection = (HttpURLConnection) url.openConnection();
                    final String json = IOUtils.toString(connection.getInputStream());
                    final Result result = GSON.fromJson(json, Result.class);
                    if (result.code == 0) {
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                show(result);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }.start();
    }

    /**
     * 显示检查结果
     * @param result
     */
    private void show(@Nullable final Result result) {
        if (result == null) {
            return;
        }
        if (result.code != 0) {
            return;
        }
        if (result.data == null) {
            return;
        }
        Resources resources = activity.getResources();
        if (result.data.hasUpdate == 0) {
            if (this.showToast) {
                Toast.makeText(activity, resources.getString(R.string.latest_toast), Toast.LENGTH_SHORT).show();
            }
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setTitle(resources.getString(R.string.update))
                .setMessage(result.data.versionLog)
                .setPositiveButton(resources.getString(R.string.download_install), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        download(result);
                    }
                })
                .setCancelable(false);
        if (result.data.forceUpdate == 0) {
            builder.setNegativeButton(resources.getString(R.string.cancel), null);
        }
        builder.show();
    }


    private void download(Result result) {
        download(result, true);
    }

    /**
     * 下载安装
     * @param isCheckWiFi 判断WiFi
     */
    private void download(final Result result, boolean isCheckWiFi) {
        if (isCheckWiFi && !AndroidUtil.isWifiConnect(activity)) {
            Resources resources = activity.getResources();
            AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                    .setTitle(resources.getString(R.string.alert))
                    .setMessage(resources.getString(R.string.wifi_alert))
                    .setNegativeButton(resources.getString(R.string.cancel), null)
                    .setPositiveButton(resources.getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            download(result, false);
                        }
                    })
                    ;
            if (result.data.forceUpdate == 0) {
                builder.setNegativeButton(resources.getString(R.string.cancel), null);
            }
            builder.show();
            return;
        }

        Intent service = new Intent(activity, DownloadService.class);
        DownloadService.Data data = new DownloadService.Data();
        data.appName = AndroidUtil.getApplicationName(activity);
        data.appVersionCode = result.data.versionCode;
        data.autoInstall = autoInstall;
        data.url = result.data.apkUrl;
        service.putExtra(DownloadService.KEY_DATA, data);
        activity.startService(service);

    }
}
